package com.dashan.backend.datastore;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.dashan.backend.XmlDeserializable;
import com.dashan.backend.XmlSerializable;


@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class DsHometown implements XmlSerializable, XmlDeserializable {
    @SuppressWarnings("unused")
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;
    
    @Persistent
    private String country = "";

    @Persistent
    private String province = "";
    
    @Persistent
    private String city = "";
    
    public DsHometown() {
    }
    public DsHometown(String country, String province, String city) {
        this.country = country;
        this.province = province;
        this.city = city;
    }
    
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
    public String getProvince() {
        return province;
    }
    public void setProvince(String province) {
        this.province = province;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    
    @Override
    public Element getXmlElement(Document xmlDoc) {
        Element root = xmlDoc.createElement("hometown");
        Element ele = null;
        
        ele = xmlDoc.createElement("country");
        ele.appendChild(xmlDoc.createTextNode(country));
        root.appendChild(ele);

        ele = xmlDoc.createElement("province");
        ele.appendChild(xmlDoc.createTextNode(province));
        root.appendChild(ele);
        
        ele = xmlDoc.createElement("city");
        ele.appendChild(xmlDoc.createTextNode(city));
        root.appendChild(ele);
        
        return root;
    }
    
    @Override
    public void fromXmlElement(Element ele) {
        NodeList e = ele.getElementsByTagName("country");
        if (e.getLength() != 0 && e.item(0).getFirstChild() != null) {
            country = e.item(0).getFirstChild().getNodeValue();;
        }
        e = ele.getElementsByTagName("province");
        if (e.getLength() != 0 && e.item(0).getFirstChild() != null) {
            province = e.item(0).getFirstChild().getNodeValue();;
        }
        e = ele.getElementsByTagName("city");
        if (e.getLength() != 0 && e.item(0).getFirstChild() != null) {
            city = e.item(0).getFirstChild().getNodeValue();;
        }
    }
    
    @Override
    public String toString() {
        return String.format("%s,%s,%s", country, province, city);
    }
}
